package de.ulrichwohlfeil.router.client;

/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;

public class Router implements ValueChangeHandler<String> {
	private static Router instance;
	private Map<String, Route> routes = new HashMap<String, Route>();
	private RouteListener fallbackListener;
	static {
		instance = new Router();
		History.addValueChangeHandler(instance);
	}

	public static Router get() {
		return instance;
	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		String path = event.getValue();
		Route currentRoute = null;
		Map<String, String> currentKeyMap = null;
		double currentMatchRate = 0;
		for (String name : routes.keySet()) {
			String matchString = "";
			Route route = routes.get(name);
			JsArrayString regResult = match("^"
					+ routes.get(name).getExpression() + "$", path);
			if (regResult == null)
				continue;
			Map<String, String> keyMap = new HashMap<String, String>();
			for (int i = 0; i < regResult.length(); i++) {
				keyMap.put(route.getKey(i), regResult.get(i));
				matchString += regResult.get(i);
			}
			double matchRate = (path.length() - matchString.length()) * 1.0
					/ path.length();
			if (matchRate > currentMatchRate) {
				currentMatchRate = matchRate;
				currentRoute = route;
				currentKeyMap = keyMap;
			}
		}
		if (currentRoute != null) {
			for (RouteListener listener : currentRoute.getListeners())
				listener.onRoute(currentRoute.getName(), currentKeyMap);
			return;
		}
		if (fallbackListener != null)
			fallbackListener.onRoute("fallback", null);
	}

	public void addRouteListener(String name, RouteListener listener) {
		if (!routeExists(name))
			throw new IllegalArgumentException("Route with the name " + name
					+ " not found");
		routes.get(name).addListener(listener);
	}

	public void addRoute(String name, String userExpression,
			RouteListener listener) {
		Route route = new Route(listener, name, userExpression);
		String modifiedExression = userExpression;
		JsArrayString result = match("\\${([\\d\\w]+)}", userExpression);
		if (result != null) {
			for (int i = 0; i < result.length(); i++) {
				modifiedExression = modifiedExression.replace("${"
						+ result.get(i) + "}", "([^/]+)");
				route.addKey(result.get(i));
			}
		}
		route.setExpression(modifiedExression);
		routes.put(name, route);
	}

	public Set<String> getRouteNames() {
		return routes.keySet();
	}

	public boolean routeExists(String name) {
		return routes.containsKey(name);
	}

	public void setFallBackRoute(RouteListener listener) {
		fallbackListener = listener;
	}

	public String getPath(String name, Map<String, String> keys) {
		if (!routeExists(name))
			throw new IllegalArgumentException("Route with the name " + name
					+ " not found");
		String path = routes.get(name).getUserExpression();
		for (String key : keys.keySet())
			path = path.replace("${" + key + "}", keys.get(key));
		return path;
	}

	protected native JsArrayString match(String pattern, String target)
	/*-{
		result = new Array();
		regPattern = new RegExp(pattern, "gi");
		matched=false;
		while(match = regPattern.exec(target))
		{
			matched=true;
			for(var i = 1; match[i] != null; i++) {
		  		result[result.length]=match[i];
			}
		}
		if(!matched)
			return null;
		return result;
	}-*/;
}
